package com.will.client;

import com.will.message.LoginRequestMessage;
import com.will.message.LoginResponseMessage;
import com.will.protocol.MessageCodecSharable;
import com.will.protocol.ProcotolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class ChatClient {
    private static final LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
    private static final MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    log.debug("222");
                    // 客户端向服务端发送登录请求后，需要等待服务端返回登录结果才能进行接下来的操作
                    // 通过 CountDownLatch 操作客户端的阻塞与唤醒
                    CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
                    AtomicBoolean LOGIN = new AtomicBoolean(false);
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            // 负责接收用户在控制台的输入
                            new Thread(() -> {
                                Scanner scanner = new Scanner(System.in);
                                System.out.println("请输入用户名：");
                                String username = scanner.next();
                                System.out.println("请输入密码：");
                                String password = scanner.next();
                                // 构造消息对象
                                LoginRequestMessage msg = new LoginRequestMessage(username, password);
                                // 发送消息
                                ctx.writeAndFlush(msg);
                                System.out.println("正在登录中。。。");
                                try {
                                    WAIT_FOR_LOGIN.await();
                                    System.out.println("后续操作中。。。");
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                // 登录失败，关闭 channel 并返回
                                if (!LOGIN.get()) {
                                    ctx.channel().close();
                                    return;
                                }
                                while (true) {
                                    System.out.println("==================================");
                                    System.out.println("send [username] [content]");
                                    System.out.println("gsend [group name] [content]");
                                    System.out.println("gcreate [group name] [m1,m2,m3...]");
                                    System.out.println("gmembers [group name]");
                                    System.out.println("gjoin [group name]");
                                    System.out.println("gquit [group name]");
                                    System.out.println("quit");
                                    System.out.println("==================================");
                                    String command = null;
                                    try {
                                        command = scanner.nextLine();
                                    } catch (Exception e) {
                                        break;
                                    }
                                }
                            }, "system in").start();
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            System.out.println("验证信息中。。。");
                            if (msg instanceof LoginResponseMessage) {
                                LoginResponseMessage message = (LoginResponseMessage) msg;
                                boolean success = message.isSuccess();
                                // 验证成功，设置成功标记
                                if (success) {
                                    LOGIN.set(true);
                                }
                                // 唤醒登录线程
                                WAIT_FOR_LOGIN.countDown();
                            }
                            super.channelRead(ctx, msg);
                        }
                    });
                }
            });
            Channel channel = bootstrap.connect("localhost", 8080).sync().channel();
            channel.closeFuture().sync();
//            ChannelFuture channelFuture = channel.closeFuture();
//            // 异步处理关闭后的操作
//            channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
//                @Override
//                public void operationComplete(Future<? super Void> future) throws Exception {
//                    System.out.println("登录失败");
//                    group.shutdownGracefully();
//                }
//            });
        } catch (Exception e) {
            log.error("client error", e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
